from google.appengine.ext import db


class User(db.Model):
    user_id = db.StringProperty(required=True)
    name = db.StringProperty(required=True)
    topics = db.ListProperty(db.Key)

    @staticmethod
    def find_by_id(user_id):
        if user_id:
            return User.gql(u'WHERE user_id = :1', user_id).fetch(1)
        else:
            return []

    def add_topic(self,topic_name):
        if topic_name:
            topics = Topic.find_by_title(topic_name)
            if len(topics)==0:
                topic = Topic(title=topic_name.lower())
                topic.put()
            else:
                topic = topics[0]
            if topic.key() not in self.topics:
                self.topics.append(topic.key())
                self.put()

    def all_topics(self):
        l_topics = []
        for key in self.topics:
            l_topics.append(Topic.get(key))
        return l_topics


class Topic(db.Model):
    title = db.StringProperty(required=True)

    @staticmethod
    def find_by_title(title):
        if title:
            return Topic.gql(u'WHERE title = :1', title.lower()).fetch(1)
        else:
            return []


class Info(db.Model):
    text = db.TextProperty(required=True)
    link = db.LinkProperty()
    users = db.ListProperty(db.Key) #stores users that was presented to this Info

    @staticmethod
    def find_by_link(url):
        if url:
            return Info.gql(u'WHERE link = :1', url).fetch(1)
        else:
            return []

class Vote(db.Model):
    good = db.BooleanProperty(required=True)
    date = db.DateProperty(required=True)
    info = db.ReferenceProperty(Info)
    user = db.ReferenceProperty(User)

class InfoTopic(db.Model):
    info = db.ReferenceProperty(Info)
    topic = db.ReferenceProperty(Topic)
    positiveCounters =db.ListProperty(db.Key) #users that voted UP for this relation
    negativeCounters =db.ListProperty(db.Key) #users that voted DOWN for this relation
